import React, { useEffect, useState } from 'react';
import {
  Text, View, TouchableOpacity, TouchableWithoutFeedback, Animated, Easing
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import styles from './styles';
import Item, { LIST_ITEM_HEIGHT } from './item';

const FoldUnFold = ({ title, style, children }) => {
  const [open, setOpen] = useState(true); // open means 'do open', which means currently it's closed
  const transition = useState(new Animated.Value(0))[0];

  const items = [
    { key: 'Sub-Item One' },
    { key: 'Sub-Item Two' },
    { key: 'Sub-Item Three' },
    { key: 'Sub-Item Four' },
  ];

  useEffect(() => {
    // height = 100;
  });

  const onPress = () => {
    const target = open ? 1 : 0;
    const elasticTimes = open ? 1 : 0;
    // console.log('onPress: ', open, transition, target);
    Animated.timing(
      transition,
      {
        toValue: target,
        duration: 400,
        easing: Easing.elastic(elasticTimes),
        useNativeDriver: false,
      }
    ).start();
    setOpen(prev => !prev);
  }

  const rotate = transition.interpolate({
    inputRange: [0, 1],
    // outputRange: [open ? '0deg' : '180deg', open ? '180deg' : '0deg']
    outputRange: ['0deg', '180deg']
  })

  const opacity = transition.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 1]
  })

  const heightValue = transition.interpolate({
    inputRange: [0, 1],
    outputRange: [0, LIST_ITEM_HEIGHT * items.length]
  })

  return (
    <>
      <View style={[styles.container, style, { borderColor: open ? 'black' : 'red' }]}>
        <TouchableWithoutFeedback onPress={onPress}>
          <View style={[styles.titleContainer, { borderBottomWidth: 0 }, styles.foldIconButtonContainer]}>
            <Text style={styles.title}>{title}</Text>
            <Animated.View
              style={[
                // { borderWidth: 1, },
                { transform: [{ rotate }] }
              ]}
            >
              <Ionicons name={'ios-chevron-down'} size={20} color={open ? 'black' : 'red'} />
            </Animated.View>
          </View>
        </TouchableWithoutFeedback>
        <Animated.View style={[
          styles.itemsA,
          { height: heightValue }
        ]}>
          {
            items.map((item, index) => (
              <Item {...{ item, index }} key={index} isLast={index === items.length - 1} />
            ))
          }
        </Animated.View>
      </View>
    </>
  );
};

export default FoldUnFold;
